package cn.nio.chat;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;

public class ChatServer {

    //2.得到一个Selector对象
    private static Selector selector;


    public static void main(String[] args) throws IOException {

        //1.得到一个ServerSocketChannel对象
        ServerSocketChannel listenerChannel = ServerSocketChannel.open();

        selector = Selector.open();

        //3.绑定端口号
        listenerChannel.bind(new InetSocketAddress(9999));

        //4.设置非阻塞方式(NIO支持阻塞/非阻塞两种方式)
        listenerChannel.configureBlocking(false);

        //5.把serverSocketChannel对象注册到Selector对象
        listenerChannel.register(selector, SelectionKey.OP_ACCEPT);

        int i = 0;
        while (true) {
            //6.1 监控客户端
            if (selector.select(2000) == 0) {
                i++;
                System.out.println("Server: 没有客户端搭理我,我就干点别的事 " + i);
                continue;
            }

            //6.2 得到SelectionKey ,判断通道里的事件
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {//客户端连接事件
                    SocketChannel socketChannel = listenerChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    System.out.println(socketChannel.getRemoteAddress().toString().substring(1) + "上线了");
                }

                if (key.isReadable()) {//读取客户端数据事件
                    readMessage(key);
                }

                //6.3 手动从集合中移除当前key,防止重复处理
                keyIterator.remove();
            }
        }
    }

    private static void readMessage(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int count = channel.read(buffer);
        if (count > 0) {
            String msg = new String(buffer.array());
            printInfo(msg);
            broadcast(channel, msg);
        }
    }

    //给所有客户端发广播
    private static void broadcast(SocketChannel except, String msg) throws IOException {
        System.out.println("服务器发送了广播");
       /* for (SelectionKey key : selector.keys()) {
            SocketChannel targetChannel = (SocketChannel) key.channel();
            if (targetChannel instanceof SocketChannel && targetChannel != except) {
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                targetChannel.write(buffer);
            }
        }*/
        for (SelectionKey key : selector.keys()) {
            //考虑协议
            SelectableChannel targetChannel = key.channel();
            if (targetChannel instanceof SocketChannel /*&& targetChannel != except*/) {
                SocketChannel destChannel = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                destChannel.write(buffer);
            }
        }
    }

    private static void printInfo(String str) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("[" + simpleDateFormat.format(new Date()) + "] ->" + str);
    }


    @Test
    public void test1(){
        String s1="s你好奥术大师多";
        String s2="s你好奥术大师多";
        String s3= "s";
        String s4=new String("s");
        System.out.println(s1.equals(s2));
        System.out.printf("%s     %s%n", Objects.equals(s2, s3), Objects.equals(s3, s4));
    }

    static {
        System.out.println("你好");
    }
}
